package cn.com.scan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import cn.com.scan.R;
import cn.com.scan.adapter.StorageAdapter;
import cn.com.scan.config.Config;
import cn.com.scan.entity.Storage;
import cn.com.scan.entity.User;
import cn.com.scan.jsonparser.ParseJson;
import cn.com.scan.netTools.RequestWebServive;
import cn.com.scan.netTools.ResultCode;
import cn.com.scan.tools.DialogUtils;
import cn.com.scan.tools.SharedPreferencesUtils;

public class LoginActivity extends BaseActivity {
    private final String StorageList = "ReturnStorageList";
    private int STORAGELIST = 101;
    private int USERLOGIN = 102;
    private Button okButton;
    private Spinner spinner;
    Storage storage;
    EditText userName;
    EditText userPWD;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DialogUtils.closeProgressDialog();
            if (msg.what == ResultCode.SUCCESS) {
                handlerDisPose(msg);
            } else if (msg.what == ResultCode.IOFAILCODE) {
                Toast.makeText(LoginActivity.this, "服务器连接失败！", Toast.LENGTH_SHORT).show();
            } else if (msg.what == ResultCode.PARSERFAILCODE) {
                Toast.makeText(LoginActivity.this, "数据解析出错！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(LoginActivity.this, "未知错误！", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        userName = (EditText) findViewById(R.id.user_name);
        userPWD = (EditText) findViewById(R.id.user_pwd);
        findViewById(R.id.login_button).setOnClickListener(viewClick);
        findViewById(R.id.exit_button).setOnClickListener(viewClick);
        findViewById(R.id.set_button).setOnClickListener(viewClick);
        spinner = (Spinner) findViewById(R.id.spinner);

        requestNet(StorageList, null, STORAGELIST);
    }

    private View.OnClickListener viewClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_button:
                    if (storage == null) {
                        Toast.makeText(LoginActivity.this, "未选择库房！", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("userName", userName.getText().toString());
                    map.put("pwd", userPWD.getText().toString());
                    requestNet("ReturnUser", map, USERLOGIN);
                    break;
                case R.id.exit_button:
                    Intent intent = new Intent();
                    intent.setAction(Config.Exit_Program_TAG);
                    sendBroadcast(intent);
                    break;
                case R.id.set_button:
                    setInputDialog();
                    break;
            }
        }
    };

    public void handlerDisPose(Message msg) {
        String str = (String) msg.obj;
        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject Json = new JSONObject(str);
                int Code = Json.getInt("CODE");
                if (Code == 0) {
                    String RESULT = Json.getString("RESULT");
                    if (msg.arg1 == STORAGELIST) {
                        storageResult(RESULT);
                    } else if (msg.arg1 == USERLOGIN){
                        loginResult(RESULT);
                    }
                } else {
                    Toast.makeText(LoginActivity.this, Json.getString("MSG"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    //库房数据
    public void storageResult(String json) {
        final List<Storage> storageList = ParseJson.parseStorageList(json);
        StorageAdapter storageAdapter = new StorageAdapter(this, storageList);
        spinner.setAdapter(storageAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                storage = storageList.get(position);
                setStorage(storage);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    //登陆结果
    public void loginResult(String  loginStr) {
        List<User> user = ParseJson.parseUser(loginStr);
        setLoginUser(user.get(0));
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }
    //设置服务器IP
    public void setInputDialog() {
        String ip = SharedPreferencesUtils.getIP(this);
        final EditText et = new EditText(this);
        et.setText(ip);
        new AlertDialog.Builder(this).setTitle("请输入服务器的IP及端口号")
                .setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Config.setIP(et.getText().toString());
                SharedPreferencesUtils.setIP(LoginActivity.this, et.getText().toString());
                requestNet(StorageList, null, STORAGELIST);
            }
        }).setNegativeButton("取消", null).show();
    }

    public void requestNet(String method, HashMap<String, Object> map, int TAG) {
        DialogUtils.showProgressDialog(LoginActivity.this);
        RequestWebServive requestWebServive = new RequestWebServive(method, handler, map, TAG);
        requestWebServive.start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(LoginActivity.this);
            alertBuilder.setTitle("提示");
            alertBuilder.setMessage("您确定退出");
            alertBuilder.setPositiveButton("退出",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();
                            Intent intent = new Intent();
                            intent.setAction(Config.Exit_Program_TAG);
                            sendBroadcast(intent);
                        }
                    });
            alertBuilder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            arg0.dismiss();
                        }
                    });
            alertBuilder.show();
        }
        return false;
    }

    @Override
    protected void broadcastExit() {
        Config.LogI("main broadcastExit");
        this.finish();
    }

    @Override
    protected void capturePic(String codeStr) {

    }
}


